package com.ruoyi.video.server.push;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.video.domain.VideoCamera;
import com.ruoyi.video.domain.VideoServer;
import com.ruoyi.video.domain.VideoStream;
import com.ruoyi.video.server.AbstractServer;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 对外推送摄像机信息和上下线消息
 */
@Service
public class PushServer extends AbstractServer {
    public static String SERVER_CODE = "push";
    public static Boolean running = false;

    private String pushUrl = "";
    private String heartUrl = "";
    private String serverId = "";

    @Override
    public String getCode() {
        return SERVER_CODE;
    }

    @Override
    public boolean start(VideoServer videoServer) {
        Map<String,String> config = videoConfigService.selectVideoServerConfig(SERVER_CODE);
        pushUrl = config.getOrDefault("pushUrl", null);
        heartUrl = config.getOrDefault("heartUrl", null);
        serverId = config.getOrDefault("serverId", "default");
        this.videoServer = videoServer;
        running = true;
        return true;
    }

    @Override
    public boolean stop(VideoServer videoServer) {
        running = false;
        return false;
    }

    @Override
    public boolean alive(VideoServer videoServer) {
        if(StringUtils.isNotEmpty(heartUrl)){
            String params = "{\"serverId\":\""+serverId+"\"}";
            if(heartUrl.toLowerCase().startsWith("https")){
                HttpUtils.sendSSLPost(heartUrl, params);
            }else{
                HttpUtils.sendPost(heartUrl, params);
            }
        }
        return running;
    }

    @Override
    public VideoStream getStream(VideoCamera videoCamera) {
        return null;
    }

    @Override
    public String snap(VideoCamera videoCamera) {
        return null;
    }

    /**
     * 推送消息
     * @param action
     * @param videoCamera
     */
    public void push(String action, Long cameraId, VideoCamera videoCamera){
        if(StringUtils.isNotEmpty(pushUrl)){
            return;
        }

        PushMessage pushMessage = PushMessage.create(action, cameraId, videoCamera);
        if(pushUrl.toLowerCase().startsWith("https")){
            HttpUtils.sendSSLPost(pushUrl, JSON.toJSONString(pushMessage));
        }else{
            HttpUtils.sendSSLPost(pushUrl, JSON.toJSONString(pushMessage));
        }
    }
}
